<template>
  <base-page class="base-form" title="我的考试" @back="onCancel()">
    <view class="main-box">
      <view class="content-box">
        <view class="content" style="margin-top: -4px">
          <u-sticky bgColor="#fff">
            <u-tabs :list="list" :is-scroll="false" style="" :current="current" @change="change"></u-tabs>
          </u-sticky>
          <!-- 未完成考试列表 -->
          <view v-show="isAnnounce == 0">
            <template v-if="dataList.length > 0">
              <view v-for="(item, index) in dataList" :key="index">
                <u-card :title="item.title" padding="30" margin="26rpx">
                  <!-- :sub-title="item.name" -->
                  <view class="" slot="body">
                    <!-- <u-parse class="u-body-item-title u-line-2" :html="item.content"></u-parse> -->
                    <view>开考时间：{{ item.timeRangesta }}</view>
                    <view>结束时间：{{ item.timeRangeend }}</view>
                  </view>
                  <view slot="foot" style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    ">
                    <view>考试时长：{{ item.duration }}分钟</view>
                    <!-- {{ checkTimeRange(item.timeRangesta, item.timeRangeend) }} -->
                    <view>
                      <view v-if="
                        checkTimeRange(item.timeRangesta, item.timeRangeend) == 1
                      " class="mini-btn" style="color: #f37b1d">考试未开始</view>
                      <button v-if="
                        checkTimeRange(item.timeRangesta, item.timeRangeend) ==
                        2 && item.hasExam == 0
                      " class="mini-btn" type="primary" size="mini" @click="publishJob(item)">
                        考试中
                      </button>
                      <view v-if="item.hasExam == 1" class="mini-btn" style="color: crimson">查看分数</view>
                      <view v-if="
                        checkTimeRange(item.timeRangesta, item.timeRangeend) == 3
                      " class="mini-btn" style="color: crimson">考试已结束</view>
                    </view>
                  </view>
                </u-card>
              </view>
            </template>
            <!-- 未完成考试列表为空时显示 -->
            <view v-else class="empty-state">
              <image src="/static/empty-image-default.png" class="empty-image"></image>
              <view class="empty-text">暂无未完成的考试</view>
            </view>
          </view>

          <!-- 考试记录列表 -->
          <view v-show="isAnnounce == 1">
            <template v-if="dataList2.length > 0">
              <view v-for="(item, index) in dataList2" :key="'index' + index">
                <u-card :title="item.title" padding="30" margin="26rpx">
                  <!-- :sub-title="item.name" -->
                  <view class="" slot="body">
                    <view>考试成绩：{{ item.userScore }}分</view>
                  </view>
                  <view slot="foot" style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    ">
                    <view>考试时长：{{ secondsToHMS(item.timeConsuming) }}</view>
                    <view> </view>
                  </view>
                </u-card>
              </view>
            </template>
            <!-- 考试记录列表为空时显示 -->
            <view v-else class="empty-state">
              <image src="/static/empty-image-default.png" class="empty-image"></image>
              <view class="empty-text">暂无考试记录</view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </base-page>
</template>

<script>
import { TPaperInfoController } from "@/api";
export default {
  data() {
    return {
      list: [
        {
          name: "未完成",
        },
        {
          name: "考试记录",
        },
      ],
      current: 0,
      swiperCurrent: 0,
      isAnnounce: 0, //0 保存 ； 1 保存并发布
      jobDetailsArr: [], //作业详情
      dataList: [],
      dataList2: [],
    };
  },
  mounted() {
    this.change(0);
  },
  methods: {
    secondsToHMS(seconds) {
      const hours = Math.floor(seconds / 3600);
      const remainingSeconds = seconds % 3600;
      const minutes = Math.floor(remainingSeconds / 60);
      const secs = remainingSeconds % 60;

      return `${hours.toString().padStart(2, "0")}:${minutes
        .toString()
        .padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
    },
    onCancel() {
      uni.switchTab({
        url: '/pages/work/index'
      })
    },
    checkTimeRange(startTimeStr, endTimeStr) {
      const parseTime = (timeStr) => {
        const isoStr = timeStr.replace(" ", "T") + "+08:00";
        const date = new Date(isoStr);
        if (isNaN(date.getTime())) {
          throw new Error(
            `Invalid date format: "${timeStr}". Use "YYYY-MM-DD HH:mm:ss"`
          );
        }
        return date;
      };

      // 解析时间
      const startTime = parseTime(startTimeStr);
      const endTime = parseTime(endTimeStr);
      const now = new Date();

      // 判断状态
      if (now < startTime) {
        return 1; // 未开始
      } else if (now >= startTime && now <= endTime) {
        return 2; // 进行中
      } else {
        return 3; // 已结束
      }
    },
    getCurrentDateTime() {
      const now = new Date();

      // 获取各时间组件
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");

      // 组合成目标格式
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    publishJob(row) {
      // uni.navigateTo({
      // 	url: `/views/forum/papering?obj=${row.id}`,
      // });
      uni.navigateTo({
        url: 
          "/views/forum/papering?obj=" +
          encodeURIComponent(
            JSON.stringify({
              id: row.id,
              duration: row.duration,
              nowStart: this.getCurrentDateTime(),
              name: row.name,
            })
          ),
      });
    },

    editJob(row) {
      // uni.navigateTo({ url: '/pages/work/workInfo/publishJob?worksObj=' + encodeURIComponent(JSON.stringify(row)) })
    },
    delJob(id) {
      // delWorkJob(id).then((res) => {
      // 	if (res.code == 200) {
      // 		uni.showToast({
      // 			title: `删除成功`
      // 		})
      // 		this.change(this.current)
      // 	}
      // }).catch((err) => {
      // 	console.error(err);
      // });
    },
    formatTime(time, time2) {
      var date = new Date(time);
      var date2 = new Date(time2);
      var time1 = date.getTime();
      var time3 = date2.getTime();

      if (Date.now() < time1) {
        return 0; //未开始考试
      } else if (Date.now() >= time1 && Date.now() <= time3) {
        return 1; //考试中
      } else {
        return 2; //考试已经结束
      }
    },

    change(index) {
      this.current = index;
      switch (index) {
        case 0:
          this.isAnnounce = 0;
          TPaperInfoController.getStudentTPaperInfoList(this)
            .then((res) => {
              this.dataList = res.filter((item) => item.hasExam === 0);
              this.dataList2 = res.filter((item) => item.hasExam === 1);
            })
            .catch((e) => { });
          // getPaperInfoByuserId().then((res) => {
          // 	if (res.code == 200) {
          // 		this.dataList = res.rows
          // 		for (var i = 0; i < this.dataList.length; i++) {
          // 			this.dataList[i].type = this.formatTime(this.dataList[i].timeRangesta,this.dataList[i].timeRangeend);

          // 		}

          // 	}
          // }).catch((err) => {
          // 	console.error(err);
          // });
          break;
        case 1:
          this.isAnnounce = 1;
          // getStuPaperList().then((res) => {
          // 	if (res.code == 200) {
          // 		this.dataList2 = res.data
          // 	}
          // }).catch((err) => {
          // 	console.error(err);
          // });
          break;
      }
    },
  },
  onLoad: function () { },
};
</script>

<style scoped>
page {
  height: 100%;
  background-color: #f2f2f2;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  min-height: 500rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
<style scoped lang="scss">
.u-card-wrap {
  background-color: $u-bg-color;
  padding: 1px;
}

.u-body-item {
  font-size: 32 rpx;
  color: #333;
  padding: 20 rpx 10 rpx;
}

.u-body-item image {
  width: 120 rpx;
  flex: 0 0 120 rpx;
  height: 120 rpx;
  border-radius: 8 rpx;
  margin-left: 12 rpx;
}
</style>